﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using System.IO.Ports;
using System.Xml;

namespace StuMana.UI
{
    public partial class Connect1 : Office2007Form
    {

        private bool co = false;
        /// Load setting 
        private Font fontForAll = null;
        private StyleManager managerStyle = new DevComponents.DotNetBar.StyleManager();



        public void ReadSetting()
        {
            XmlReader reader = XmlReader.Create("Settings.xml");
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element
                && reader.Name == "font")
                {
                    string name = reader.GetAttribute(0).ToString();
                    string style = reader.GetAttribute(1).ToString();
                    float size = float.Parse(reader.GetAttribute(2).ToString());
                    if (style == "Bold")
                        fontForAll = new System.Drawing.Font(reader.GetAttribute(0).ToString(), size, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                    if (style == "Italic")
                        fontForAll = new System.Drawing.Font(reader.GetAttribute(0).ToString(), size, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                    if (style == "Regular")
                        fontForAll = new System.Drawing.Font(reader.GetAttribute(0).ToString(), size, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                    if (style == "Strikeout")
                        fontForAll = new System.Drawing.Font(reader.GetAttribute(0).ToString(), size, System.Drawing.FontStyle.Strikeout, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                    if (style == "Underline")
                        fontForAll = new System.Drawing.Font(reader.GetAttribute(0).ToString(), size, System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, ((byte)(0)));

                    while (reader.NodeType != XmlNodeType.EndElement)
                    {
                        reader.Read();
                        if (reader.Name == "managerstyle" && reader.NodeType == XmlNodeType.Element)
                        {
                            reader.Read();
                            string stylemana = reader.Value.ToString();

                            if (stylemana == "Office2007Blue")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2007Blue;
                            if (stylemana == "Office2007Silver")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2007Silver;
                            if (stylemana == "Office2007Black")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2007Black;
                            if (stylemana == "Windows7Blue")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Windows7Blue;
                            if (stylemana == "Office2007VistaGlass")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2007VistaGlass;
                            if (stylemana == "Office2010Silver")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2010Silver;
                            if (stylemana == "Office2010Blue")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2010Blue;
                            if (stylemana == "Office2010Black")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2010Black;
                        }
                    }
                }
            }
            reader.Close();
        }

        public void ConfigSetting()
        {
            ReadSetting();
            for (int i = 0; i < Controls[0].Controls[2].Controls.Count; i++)
            {
                if (Controls[0].Controls[2].Controls[i] is LabelX)
                {
                    Controls[0].Controls[2].Controls[i].Font = fontForAll;
                }
            }

            styleManager1 = managerStyle;
        }
        /// End Load setting 

        public delegate void AsyncCallback(IAsyncResult ar);
        public delegate void AddTolstDiscoveredDevices(object o);

        private UdpState GlobalUDP;

        public Services.COM connect;
        private Timer readTimer;
        Services.SL025M rfid_reader = new Services.SL025M();

        private int size;
        private byte[] serial_buff = new byte[40];
      
       
        /// <summary>
        ///  UDP
        /// </summary>
        struct UdpState
        {
            public System.Net.IPEndPoint EP;
            public System.Net.Sockets.UdpClient UDPClient;
        }

        private void cmdDiscoverDevices_Click(object sender, EventArgs e)
        {
            try
            {
                // Clear the listbox of all current discovery responses
                lvExDevice.Items.Clear();
                // Try to send the discovery request message
                byte[] DiscoverMsg = Encoding.ASCII.GetBytes("Discovery: Who is out there?");
                GlobalUDP.UDPClient.Send(DiscoverMsg, DiscoverMsg.Length, new System.Net.IPEndPoint(System.Net.IPAddress.Parse("255.255.255.0"), 30303));
            }
            catch
            {
                MessageBox.Show("Unable to transmit discovery message.  Check network connectivity and ensure that no other instances of this program are running.", "Error", MessageBoxButtons.OK);
                return;
            }
        }

        public void AddDiscoveryEntry(object o)
        {
            //lstDiscoveredDevices.Items.Add(o);
            lvExDevice.Items.Add(new ListViewItem(((string)(o)).Split('\n')));
            //MessageBox.Show((string)(o),"Warning");
        }

        public void ReceiveCallback(IAsyncResult ar)
        {
            UdpState MyUDP = (UdpState)ar.AsyncState;

            // Obtain the UDP message body and convert it to a string, with remote IP address attached as well
            string ReceiveString = Encoding.ASCII.GetString(MyUDP.UDPClient.EndReceive(ar, ref MyUDP.EP));
            ReceiveString = MyUDP.EP.Address.ToString() + "\n" + ReceiveString.Replace("\r\n", "\n");

            // Configure the UdpClient class to accept more messages, if they arrive
            MyUDP.UDPClient.BeginReceive(ReceiveCallback, MyUDP);

            // Write the received UDP message text to the listbox in a thread-safe manner
            //lstDiscoveredDevices.Invoke(new AddTolstDiscoveredDevices(AddDiscoveryEntry), ReceiveString);
            lvExDevice.Invoke(new AddTolstDiscoveredDevices(AddDiscoveryEntry), ReceiveString);
        }

      

        /*--------------------------------------------------------------*/
      
        // timer handler
        private void readTimer_Tick(object sender, EventArgs e)
        {
            rfid_reader.selectCard();
            size = connect.getArray(serial_buff);

            if (size == 5000)
            {
                readTimer.Enabled = false;
              //  lb_status.Text = "No signal";
                labelItemStatus.Text = "No signal";

            }
            else
            {
             //   lb_status.Text = "";
                for (int cnt = 0; cnt < size; cnt++)
                {
               //     lb_status.Text += Convert.ToString(serial_buff[cnt], 16).PadLeft(2, '0').PadRight(3, ' ').ToUpper();
                   labelItemStatus.Text += Convert.ToString(serial_buff[cnt], 16).PadLeft(2, '0').PadRight(3, ' ').ToUpper();
                }
            }
        }


     


        private void Connect1_Load(object sender, EventArgs e)
        {
            ConfigSetting();
            co = true;
            
        }


        

        public Connect1()
        {
            InitializeComponent();
            Connect_initial();
        }

        private void Connect_initial()
        {
            string[] s = SerialPort.GetPortNames();
            int i = 0;

            cmbExBaudrate.Items.Clear();
            cmbExBaudrate.Items.Add("1200");
            cmbExBaudrate.Items.Add("2400");
            cmbExBaudrate.Items.Add("4800");
            cmbExBaudrate.Items.Add("9600");
            cmbExBaudrate.Items.Add("19200");
            cmbExBaudrate.Items.Add("38400");
            cmbExBaudrate.Items.Add("57600");
            cmbExBaudrate.Items.Add("115200");
            cmbExBaudrate.Items.Add("230400");
            cmbExBaudrate.SelectedIndex = 4;

            cmbExComPort.Items.Clear();
            foreach (string port in s)
            {
                cmbExComPort.Items.Add(s[i]);
                i++;
            }
            if (cmbExComPort.Items.Count != 0)
                cmbExComPort.SelectedIndex = 0;
        }



        private void btnConnect_Click(object sender, EventArgs e)
        {
           
            try
            {
                connect = new Services.COM(cmbExComPort.SelectedItem.ToString(), int.Parse(cmbExBaudrate.SelectedItem.ToString()));
                rfid_reader.get_connect(connect);
                btnConnect.Enabled = false;
                btnDisconnect.Enabled = true;
               // readTimer.Enabled = true;
                //ts_connect.Text = "COM: " + cmbExComPort.SelectedItem.ToString();
               labelItemConnect.Text = "COM: " + cmbExComPort.SelectedItem.ToString();
                
            }
            catch (Exception es)
            {
               // ts_connect.Text = "COM Error: " + es.Message;
                labelItemConnect.Text = "COM Error: " + es.Message;
            }
        
        }

        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            
            try
            {
               // readTimer.Enabled = false;
                if (!btnConnect.Enabled)
                    connect.closeCOMPort();
                // button connect disable
                btnConnect.Enabled = true;
                //button disconnect
                btnDisconnect.Enabled = false;
                //status connect
              //  lb_status.Text = "None";
                labelItemStatus.Text = "None";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "COM Error");
            }
        
        }

        private void Connect1_FormClosed(object sender, FormClosedEventArgs e)
        {
           
            Application.ExitThread();
            Application.Exit();
        }

        private void Connect1_FormClosing(object sender, FormClosingEventArgs e)
        {
        
            Application.ExitThread();
            Application.Exit();
        }

        private void Connect1_Resize(object sender, EventArgs e)
        {
            int w = lvExDevice.Size.Width;
            int widthC = ((int)w / 4);
            if (co == true)
            {
                lvExDevice.Columns[0].Width = widthC;
                lvExDevice.Columns[1].Width = widthC;
                lvExDevice.Columns[2].Width = widthC;
                lvExDevice.Columns[3].Width = widthC;
            }
        }

        private void lvExDevice_ItemActivate(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("http://" + lvExDevice.SelectedItems[0].Text);
        }

      
       

    }
}
